package com.xm.permission;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

public class XMPermissionProxy extends UniModule {
    private static final String TAG = "XMPermissionProxy";
    private Handler handler = new Handler(Looper.getMainLooper());
    private static final int TIMEOUT_SECONDS = 15000; // 15秒超时

    @UniJSMethod(uiThread = true)
    public void requestAutoStartPermission(UniJSCallback callback) {
        Activity activity = (Activity) mUniSDKInstance.getContext();
        
        // 检查无障碍服务是否开启
        if (!PermissionHelper.isAccessibilitySettingsOn(activity)) {
            // 打开无障碍设置
            PermissionHelper.openAccessibilitySettings(activity);
            
            if (callback != null) {
                try {
                    JSONObject result = new JSONObject();
                    result.put("success", false);
                    result.put("tips", "请先开启无障碍服务");
                    callback.invoke(result);
                } catch (JSONException e) {
                    callback.invoke(false);
                }
            }
            return;
        }
        // 注册回调
        PermissionHelper.setResultCallback(new PermissionCallback() {
            @Override
            public void onResult(boolean success, String tips) {
                Log.i(TAG, "自启动权限请求结果: " + success + ", 提示: " + tips);
                
                if (callback != null) {
                    try {
                        JSONObject result = new JSONObject();
                        result.put("success", success);
                        result.put("tips", tips);
                        callback.invoke(result);
                    } catch (JSONException e) {
                        Log.e(TAG, "创建回调JSON对象失败", e);
                        callback.invoke(success);
                    }
                }
            }
        });
        
        // 请求权限
        AutoStartHelper.getInstance().getAutoStartPermission(activity);
    }
    
    @UniJSMethod(uiThread = true)
    public void checkAccessibilityEnabled(UniJSCallback callback) {
        Activity activity = (Activity) mUniSDKInstance.getContext();
        boolean enabled = PermissionHelper.isAccessibilitySettingsOn(activity);
        
        if (callback != null) {
            try {
                JSONObject result = new JSONObject();
                result.put("success", enabled);
                result.put("tips", enabled ? "无障碍服务已启用" : "无障碍服务未启用");
                callback.invoke(result);
            } catch (JSONException e) {
                callback.invoke(enabled);
            }
        }
    }
    
    @UniJSMethod(uiThread = true)
    public void openAccessibilitySettings(UniJSCallback callback) {
        Activity activity = (Activity) mUniSDKInstance.getContext();
        PermissionHelper.openAccessibilitySettings(activity);
        
        if (callback != null) {
            try {
                JSONObject result = new JSONObject();
                result.put("success", true);
                result.put("tips", "已打开无障碍服务设置");
                callback.invoke(result);
            } catch (JSONException e) {
                callback.invoke(true);
            }
        }
    }

    /**
     * 执行点击操作
     * @param x 横坐标
     * @param y 纵坐标
     * @param callback 回调
     */
    @UniJSMethod(uiThread = true)
    public void performClick(float x, float y, UniJSCallback callback) {
        Log.i(TAG, "uni-app请求点击操作: (" + x + ", " + y + ")");
        
        // 检查无障碍服务
        if (!PermissionHelper.isAccessibilitySettingsOn(mUniSDKInstance.getContext())) {
            returnResult(callback, false, "无障碍服务未开启，请先开启服务", "click");
            return;
        }
        
        // 执行点击
        GestureController.performClick(x, y, new GestureController.GestureCallback() {
            @Override
            public void onGestureResult(boolean success, String message, String operationType) {
                Log.i(TAG, "点击操作结果: " + success + ", 消息: " + message);
                returnResult(callback, success, message, operationType);
            }
        });
    }

    /**
     * 执行滑动操作
     * @param x1 起始X坐标
     * @param y1 起始Y坐标
     * @param x2 结束X坐标
     * @param y2 结束Y坐标
     * @param callback 回调
     */
    @UniJSMethod(uiThread = true)
    public void performSwipe(float x1, float y1, float x2, float y2, UniJSCallback callback) {
        Log.i(TAG, "uni-app请求滑动操作: (" + x1 + ", " + y1 + ") → (" + x2 + ", " + y2 + ")");
        
        // 检查无障碍服务
        if (!PermissionHelper.isAccessibilitySettingsOn(mUniSDKInstance.getContext())) {
            returnResult(callback, false, "无障碍服务未开启，请先开启服务", "swipe");
            return;
        }
        
        // 执行滑动
        GestureController.performSwipe(x1, y1, x2, y2, new GestureController.GestureCallback() {
            @Override
            public void onGestureResult(boolean success, String message, String operationType) {
                Log.i(TAG, "滑动操作结果: " + success + ", 消息: " + message);
                returnResult(callback, success, message, operationType);
            }
        });
    }

    /**
     * 返回结果给uni-app
     */
    private void returnResult(UniJSCallback callback, boolean success, String message, String operationType) {
        if (callback != null) {
            try {
                JSONObject result = new JSONObject();
                result.put("success", success);
                result.put("message", message);
                result.put("type", operationType);
                callback.invoke(result);
            } catch (JSONException e) {
                Log.e(TAG, "创建JSON结果时出错", e);
                try {
                    JSONObject errorResult = new JSONObject();
                    errorResult.put("success", false);
                    errorResult.put("message", "内部错误: " + e.getMessage());
                    errorResult.put("type", operationType);
                    callback.invoke(errorResult);
                } catch (JSONException ex) {
                    callback.invoke(false);
                }
            }
        }
    }
} 